package com.hitqz.robot.biz.bean;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.dto.RobotClientSummaryDto;
import com.hitqz.robot.api.business.dto.RobotJobDto;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.api.business.entity.RobotJobEntity;
import com.hitqz.robot.api.business.entity.TicketsEntity;
import com.hitqz.robot.api.business.enums.TicketsStatusEnum;
import com.hitqz.robot.biz.service.RobotJobService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.biz.service.TicketsService;
import com.hitqz.robot.biz.service.TicketsTaskService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.daemon.quartz.service.SysJobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author xupkun
 * @date 2024/8/6
 */
@Component("robotJob")
@RequiredArgsConstructor
@Slf4j
public class RobotJobSchedule {

    private final RobotJobService robotJobService;

    private final SysJobService sysJobService;

    private final TicketsService ticketsService;

    private final RobotService robotService;

    /**
     * 执行任务
     *
     * @param jobId robotJobEntity.id
     * @return
     */
    public String execute(String jobId) {
      /*  TicketsEntity tickets = ticketsService.getById(ticketsId);
        List<TicketsEntity> list = ticketsService.lambdaQuery().gt(TicketsEntity::getId,
                ticketsId).eq(TicketsEntity::getAllotRobotSn,tickets.getAllotRobotSn() ).list();
        if(!list.isEmpty()){
            return R.failed("该机器已开始其他工单，不能恢复工单");
        }
        Cache<String, RobotClientSummaryDto> posInfoDtoCache = SpringUtil.getBean("robotCache");

        RobotClientSummaryDto robotClientSummaryDto = posInfoDtoCache.getIfPresent(tickets.getAllotRobotSn());
        if(Objects.isNull(robotClientSummaryDto)&&robotClientSummaryDto.getStatus()!=null&&robotClientSummaryDto
        .getStatus().getEmergencyStop()==1){
            return R.failed("该机器处于急停状态，不能恢复工单");
        }*/

        // 查询
        RobotJobEntity robotJobEntity = robotJobService.getById(jobId);

        RobotEntity entity = new RobotEntity();
        entity.setGroupId(robotJobEntity.getGroupId());
        List<RobotEntity> robotEntities = robotService.lambdaQuery(entity).list();

        if (robotEntities == null || robotEntities.isEmpty()) {
            log.error("执行组内没有要执行的机器：groupId:{}", robotJobEntity.getGroupId());
            return "fail";
        }
       RobotEntity robotEntity = robotEntities.get(0);


        String robotSn = robotEntity.getRobotSn();
        TicketsEntity ticketsEntity = ticketsService.getOne(
                new LambdaQueryWrapper<TicketsEntity>()
                        .eq(TicketsEntity::getAllotRobotSn, robotSn)
                        .gt(TicketsEntity::getCreateTime, "2025-06-13 23:00:00")
                        .orderByDesc(TicketsEntity::getId)
                        .last("limit 1"));
        if (ticketsEntity != null && ticketsEntity.getStatus() == TicketsStatusEnum.STATUS_EXECUTING.getCode()) {
            log.error("当前机器正在执行 {},请稍后再试",ticketsEntity.getId());
            return "fail";
        }

//        Long count = ticketsService.count(
//                new LambdaQueryWrapper<TicketsEntity>()
//                        .eq(TicketsEntity::getAllotRobotSn, robotSn)
//                        .eq(TicketsEntity::getStatus, TicketsStatusEnum.STATUS_PAUSED.getCode())
//                        .gt(TicketsEntity::getCreateTime, "2025-06-13 23:00:00")
//                        .orderByDesc(TicketsEntity::getId)
//        );
//        if (count > 0) {
//            log.error("当前机器有暂停的任务，请先停止再执行新任务");
//            return "fail";
//        }

        Cache<String, RobotClientSummaryDto> posInfoDtoCache = SpringUtil.getBean("robotCache");
        RobotClientSummaryDto robotClientSummaryDto = posInfoDtoCache.getIfPresent(robotEntity.getRobotSn());
        if (robotClientSummaryDto != null && robotClientSummaryDto.getStatus() != null &&
                robotClientSummaryDto.getStatus().getEmergencyStop() == 1) {
            log.error("当前机器处于急停状态，请先释放急停按钮");
            return "fail";
        }


        if (robotJobEntity != null) {
            RobotJobDto robotJobDto = new RobotJobDto();
            robotJobDto.setId(robotJobEntity.getId());
            SpringUtil.getApplicationContext().publishEvent(robotJobDto);
        }
        return "success";
    }


    /**
     * 重复查询是否存在任务-执行
     *
     * @param content
     * @return
     */
    public String repeatTask(String content) {


        return "success";
    }


}
